package com.jxb.e20241230;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 *
 * 1 2 3
 * 4 5 6
 * 7 8 9
 *
 * 思路：
 *  1：先计算出矩阵层数
 *  2：设置层数计数器
 *  3：以层数进行遍历，分别计算从左到右、从上到下，从右到左，从下到上
 *
 *
 */
public class SpiralMatrix1_54 {

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> integers = spiralOrder(matrix);
        System.out.println("---");
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return res;
        }
        int columLength = matrix.length;
        int rowLength = matrix[0].length;
        //矩阵层数
        int count = (Math.min(columLength,rowLength) + 1)/2;
        //层数指示器
        int piles = 0;
        //循环遍历
        // * 1 2 3
        // * 4 5 6
        // * 7 8 9
        while (piles < count) {
            //从右到左
            for (int i = piles;i<columLength-piles;i++) {
                res.add(matrix[piles][i]);
            }
            //从上到下
            //6(1,2),9(2,2)
            for (int i = piles + 1;i<rowLength - piles;i++) {
                res.add(matrix[i][(columLength - 1) - piles]);
            }
            //从右到左
            //8(2,1),7(2,0)
            for (int i = (columLength - 1)-(piles + 1);i>=piles && (rowLength - 1 - piles != piles);i--) {
                res.add(matrix[(columLength - 1 - piles) - piles][i]);
            }
            //从下到上
            //4(1,0)
            for (int i = (rowLength - 1)-(piles+1);i>=piles+1 && (columLength - 1 - piles != piles);i--) {
                res.add(matrix[i][piles]);
            }
            piles++;
        }
        return res;
    }


}
